package com.touchportfolio.controller
{
	import com.touchportfolio.model.ApplicationModel;
	import com.touchportfolio.view.Row;
	import com.touchportfolio.view.RowBasic;
	
	import flash.events.GestureEvent;
	
	import flash.events.GestureEvent;
	import flash.events.TouchEvent;
	import flash.events.TransformGestureEvent;
	import flash.ui.Multitouch;
	import flash.ui.MultitouchInputMode;
	
	public class TouchController
	{
		private var _appModel:ApplicationModel = ApplicationModel.getInstance();
		private var _row:RowBasic;
		
		public function TouchController(row:RowBasic)
		{
			Multitouch.inputMode = MultitouchInputMode.GESTURE;
			
			_row = row;
			
			_row.addEventListener(GestureEvent.GESTURE_TWO_FINGER_TAP, onTwoFingerTap);
			_row.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoomHandler);
			_row.addEventListener(TouchEvent.TOUCH_TAP, onTapHandler);
			_row.addEventListener(TransformGestureEvent.GESTURE_SWIPE, onSwipeHandler);
			//_row.addEventListener(TransformGestureEvent, onSwipeHandler);
			_row.addEventListener(TouchEvent.TOUCH_BEGIN, onBeginTouchHandler);
			_row.addEventListener(TouchEvent.TOUCH_END, onEndTouchHandler);
		}

		private function onZoomHandler(e:TransformGestureEvent):void
		{
			if(!_appModel.activeRowOpen && !_appModel.slideshowReady && _appModel.activeRow == _row.node.rowId)
			{
				_appModel.activeRowOpen = true;
				trace("[TOUCH] pinch open");
			}
			
			else if((_appModel.activeRow == _row.node.rowId) && _appModel.activeRowOpen && _appModel.slideshowReady) 
			{ 
				_appModel.activeRowOpen = false;  
				trace("[TOUCH] pinch close");
			}
		}
		
		private function onTapHandler(e:TouchEvent):void
		{
			if(!_appModel.activeRowOpen && !_appModel.activeRowOpen && _appModel.activeRow == _row.node.rowId)
			{
				_appModel.activeRowOpen = true;
				trace("[TOUCH] tap to open");
			}
			
		}
		
		private function onBeginTouchHandler(e:TouchEvent):void
		{
			if(_appModel.activeRowOpen)
			{
				_appModel.slideshowDrag = true;
				trace("[TOUCH] begin touch");
			}
		}
		
		private function onEndTouchHandler(e:TouchEvent):void
		{
			if(_appModel.activeRowOpen)
			{
				_appModel.slideshowDrag = false;
				trace("[TOUCH] end touch");
			}
		}
		
		private function onSwipeHandler(e:TransformGestureEvent):void
		{
			trace("[TOUCH] swipe");
			
			if(e.offsetX > 0)
			{
				_appModel.activeImage--;
			}
			else
			{
				_appModel.activeImage++;
			}
		}
		
		private function onTwoFingerTap(e:GestureEvent):void
		{
			if((_appModel.activeRow == _row.node.rowId) && _appModel.activeRowOpen && _appModel.slideshowReady) 
			{ 
				trace("[TOUCH] two finger tap");
				_appModel.activeRowOpen = false;  
			}
		}
	}
}